package org.xiaohanghu.starter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaohanghu
 * */
public class IOUtils {

	public static List<String> readBySeparator(Reader reader)
			throws IOException {
		List<String> result = new ArrayList<String>();
		StringBuilder stringBuilder = new StringBuilder();
		int i = reader.read();
		while (i != -1) {
			char c = (char) i;
			switch (c) {
			case ' ':
			case '\r':
			case '\n':
				if (stringBuilder.length() > 0) {
					result.add(stringBuilder.toString());
					stringBuilder = new StringBuilder();
				}
				break;
			default:
				stringBuilder.append(c);
			}
			i = reader.read();
		}
		if (stringBuilder.length() > 0) {
			result.add(stringBuilder.toString());
			stringBuilder = null;
		}

		return result;
	}

	public static List<String> readBySeparator(Reader reader, char[] separators)
			throws IOException {
		List<String> result = new ArrayList<String>();
		StringBuilder stringBuilder = new StringBuilder();
		int i = reader.read();
		while (i != -1) {
			char c = (char) i;
			boolean isSeparator = false;
			for (char separator : separators) {
				if (c == separator) {
					isSeparator = true;
					break;
				}
			}
			if (isSeparator) {
				if (stringBuilder.length() > 0) {
					result.add(stringBuilder.toString());
					stringBuilder = new StringBuilder();
				}
			} else {
				stringBuilder.append(c);
			}

			i = reader.read();
		}
		return result;
	}

	public static Reader createrResder(InputStream inputStream, String encoding) {
		InputStreamReader inputStreamReader;
		try {
			inputStreamReader = new InputStreamReader(inputStream, encoding);
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException(e);
		}
		Reader reader = new BufferedReader(inputStreamReader);
		return reader;
	}

	public static Reader createrResder(String text) {
		Reader reader = new StringReader(text);
		return reader;
	}

}
